<?php

/**
 * 活动信息表
 */
use Common\Bridge;
use lib\core\AdminAction;

define('SITE_AUTH', 'vote-list');
require('../../../common.inc.php');

class vote extends AdminAction
{
    private $pdo_r;
    private $primary_key = 'Id';
    private $list_url = '/data/modules/act/vote.php';

    public function doDefault()
    {
        $param['Id'] = (int)$_GET['Id'];
        $param['ShopId'] = (int)($_GET['ShopId']);
        $param['Status'] = (int)($_GET['Status']);
        $param['Name'] = trim($_GET['Name']);

        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "1";
        if ($param['Id'] > 0) {
            $where .= " AND Id = " . $param['Id'];
        }

        if ($param['Name'] != '') {
            $where .= " AND Name LIKE '%" . $param['Name'] . "%'";
        }

        if ($param['ShopId'] > 0) {
            $where .= " AND ShopId = " . $param['ShopId'];
        }
        if ($param['Status'] > 0) {
            $where .= " AND Status = " . $param['Status'];
        }

        $primary_key = $this->primary_key;
        $count_sql = "SELECT COUNT(*) AS `num` FROM `VoteActive` WHERE $where";

        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $sql = "SELECT * FROM `VoteActive` WHERE $where LIMIT $offset, $limit";
        $data = $this->readDb($sql);

        $catedata = \Center\Category::getAllCate();
        $cate = $catedata['data'];
        $smarty = $this->app->page();
        if ($count > 0) {
            if (!empty($data)) {
                $smarty->value('list', $data);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }

        $smarty->value('param', $param);
        $smarty->value('cate', $cate);
        $smarty->value('status_arr', [1 => '投票中', 2 => '领奖', 3 => '已结束']);
        $smarty->output('act/vote.tpl');
    }

    /**
     * 利用SQL语句读取数据库并返回相应数据
     *
     * @param $sql
     * @return mixed
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_W);
        }

        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }

    /**
     *
     */
    public function doEdit()
    {
        $id = (int)$_GET['Id'];
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }

        $sql = "SELECT * FROM VoteActive WHERE Id = $id";
        $list = $this->readDb($sql);

        $smarty = $this->app->page();
        $catedata = \Center\Category::getAllCate();
        $cate = $catedata['data'];
        $smarty->value('cate', $cate);
        $smarty->value('info', current($list));
        $smarty->output('act/voteedit.tpl');
    }

    /**
     *
     */
    public function doShopList()
    {
        $id = (int)$_GET['Id'];
        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }
        $count_sql = "SELECT COUNT(*) AS `num` FROM `VoteActiveShop` WHERE ActiveId = $id";
        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $smarty = $this->app->page();
        $sql = "SELECT * FROM VoteActiveShop WHERE ActiveId=$id  order by VoteNum DESC, Sort Desc limit $offset, $limit";
        $list = $this->readDb($sql);
        if ($count > 0) {
            if (!empty($data)) {
                $smarty->value('list', $data);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }

        $smarty->value('list', $list);
        $smarty->value('id', $id);
        $smarty->output('act/shoplist.tpl');
    }

    public function doAdd()
    {
        $smarty = $this->app->page();
//        $smarty->value('info', current($list));
        $catedata = \Center\Category::getAllCate();
        $cate = $catedata['data'];
        $smarty->value('cate', $cate);
        $smarty->output('act/voteadd.tpl');
    }

    public function doUpdate()
    {
        $id = intval($_POST['Id']);
        if (empty($id) || empty($_POST['Name'])) {
            HDshowMsg('修改失败1！', ['type' => 'error', 'url' => $this->list_url]);
        }

        $data = [
            'CityId' => intval($_POST['CityId']),
            'CateId' => intval($_POST['CateId']),
            'Name' => trim($_POST['Name']),
            'Description' => trim($_POST['Description']),
            'StartTime' => trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'Status' => intval($_POST['Status']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        $rel = \Center\VoteActive::update($id, $data);
        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doVoteEnd()
    {
        $id = intval($_GET['Id']);
        if (empty($id)) {
            HDshowMsg('参数错误！', ['type' => 'error', 'url' => $this->list_url]);
        }
        //修改状态
        $data = [
            'Status' => \Center\VoteActive::STATUS_REWARD,
        ];
        $rel = \Center\VoteActive::update($id, $data);
        //统计排名
        $sql = "SELECT * FROM VoteActiveShop WHERE ActiveId=$id  order by VoteNum DESC";
        $list = $this->readDb($sql);
        $i = 1;
        $tmp_vn = $list[0]['VoteNum'];
        $vasdata = [];
        foreach ($list as $k => $v) {
            $vasdata[$k] = $v;
            if ($v['VoteNum'] == $tmp_vn) {
                $vasdata[$k]['Rank'] = $i;
            } elseif ($v['VoteNum'] < $tmp_vn) {
                $i ++;
                $vasdata[$k]['Rank'] = $i;
                $tmp_vn = $v['VoteNum'];
            }
        }
        foreach ($vasdata as $v) {
            if ($v['Rank'] < 4) {
                $upsql = "UPDATE VoteActiveInfo set RewardStatus = 1, RewardRank = {$v['Rank']} where ShopId = {$v['ShopId']} and ActiveId = {$v['ActiveId']}";
                $this->readDb($upsql);
            } else {
                $upsql = "UPDATE VoteActiveInfo set RewardRank = {$v['Rank']} where ShopId = {$v['ShopId']} and ActiveId = {$v['ActiveId']}";
                $this->readDb($upsql);
            }
        }
        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doRewardEnd()
    {
        $id = intval($_GET['Id']);
        if (empty($id)) {
            HDshowMsg('参数错误！', ['type' => 'error', 'url' => $this->list_url]);
        }

        $data = [
            'Status' => \Center\VoteActive::STATUS_FINISH,
        ];
        $rel = \Center\VoteActive::update($id, $data);
        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doUpdateShop()
    {
        $id = intval($_POST['Id']);
        $shopid = intval($_POST['ShopId']);
        $url = $this->list_url . '?do=ShopList&Id=' . $id;
        if (empty($id) || empty($shopid)) {
            HDshowMsg('修改失败1！', ['type' => 'error', 'url' => $url]);
        }
        $data = [
            'ActiveId' => intval($_POST['Id']),
            'ShopId' => intval($_POST['ShopId']),
            'Sort' => intval($_POST['Sort']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];

        $res = \Center\VoteActiveShop::getList(['ActiveId' => $id, 'ShopId' => $shopid]);
        if ($res['count'] > 0) {
            $rel = \Center\VoteActiveShop::update($res['data'][0]['Id'], $data);
        } else {
            $rel = \Center\VoteActiveShop::add($data);
        }

        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $url]);
        } else {
            HDshowMsg('修改失败?！', ['type' => 'error', 'url' => $url]);
        }
    }

    public function doDelShop()
    {
        $id = intval($_GET['aid']);
        $vasid = intval($_GET['Id']);
        $url = $this->list_url . '?do=ShopList&Id=' . $id;
        $rel = \Center\VoteActiveShop::delete($vasid);

        if ($rel) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $url]);
        } else {
            HDshowMsg('修改失败?！', ['type' => 'error', 'url' => $url]);
        }
    }

    public function doInput()
    {
        if (empty($_POST['CateId'])) {
            HDshowMsg('添加失败！', ['type' => 'error', 'url' => $this->list_url]);
        }

        $data = [
            'CityId' => intval($_POST['CityId']),
            'CateId' => intval($_POST['CateId']),
            'Name' => trim($_POST['Name']),
            'Description' => trim($_POST['Description']),
            'StartTime' => trim($_POST['StartTime']),
            'EndTime' => trim($_POST['EndTime']),
            'Status' => intval($_POST['Status']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        $id = Center\VoteActive::add($data);
        if ($id !== false && $id > 0) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }
}

$app->run();